import os, shutil
from project import Main
from win32com import client as wc
import fnmatch


def fun(file_name, wordapp):
    # 源文件
    src_file = Main.file_path + "/" + file_name
    # 正常文件
    normal = Main.result_path + "/DOC" + "/normal"
    # 失败文件
    wrong = Main.result_path + "/DOC" + "/wrong"
    # 失败日志
    log = Main.result_path + "/DOC" + "/wrong.txt"

    # txt文件
    target = Main.result_path + "/DOC" + "/txt"

    if not os.path.exists(normal):
        os.makedirs(normal)  # 创建路径
    if not os.path.exists(target):
        os.makedirs(target)  # 创建路径
    if not os.path.exists(wrong):
        os.makedirs(wrong)  # 创建路径

    try:
        # 得到一个新的文件名,把原文件名的后缀改成txt
        new_txt_name = ''
        if fnmatch.fnmatch(file_name, '*.doc'):
            new_txt_name = file_name[:-4] + '.txt'
        else:
            new_txt_name = file_name[:-5] + '.txt'

        word_to_txt = target + "/" + new_txt_name
        doc = wordapp.Documents.Open(src_file)
        # 为了让python可以在后续操作中r方式读取txt和不产生乱码，参数为4
        doc.SaveAs(word_to_txt, 4)
        doc.Close()
    except BaseException as e:
        shutil.copyfile(src_file, wrong + "/" + file_name)

        with open(log, "a") as file:  # "a"代表追加内容
            file.write(file_name + " " + repr(e) + "\n")

    else:
        shutil.move(src_file, normal + "/")
